<?php

namespace app\admin\controller\mox\inheritor;

use app\common\controller\Backend;

/**
 * 木偶戏非遗传入
 *
 * @icon fa fa-circle-o
 */
class Info extends Backend
{

    /**
     * Info模型对象
     * @var \app\admin\model\mox\inheritor\Info
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mox\inheritor\Info;
    }
    public function index()
    {
        // 安全过滤输入参数
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            // 获取排除的ID参数，确保是正整数 (default=0表示不排除)
            $excludeId = $this->request->request('exclude_id/d', 0);
            $searchValue = $this->request->request('searchValue');
            // 构建查询条件
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // 初始化查询构造器
            $query = $this->model
                ->with(['user', 'videofilename'])
                ->where($where);
            // 添加排除ID条件（只有当exclude_id有效时）
            if ($excludeId > 0 || $searchValue) {
                $query->where($this->model->getTable() . '.id', '<>', $excludeId);
                if ($searchValue) {
                    $searchID = explode(',', $searchValue);
                    $query->where($this->model->getTable() . '.id', 'in', $searchID);
                }
                if ($excludeId > 0) {
                    $query->where($this->model->getTable() . '.id', '<>', $excludeId);
                }
                $list = $query
                    ->order($sort, $order)
                    ->paginate($limit);
            } else {
                $list = $query
                    ->order($sort, $order)
                    ->paginate($limit)
                    ->each(function ($item) {
                        // $relatedpersons = explode(',', $item['related_persons']);
                        // $item['relatedpersons'] = $this->model->where('id', 'in', $relatedpersons)->select();
                        // 关联剧目
                        $label = explode(',', $item['label_id']);
                        $item['label'] = model('app\admin\model\mox\inheritor\Label')->where('id', 'in', $label)->select();
                        $related_plays = explode(',', $item['related_plays']);
                        $item['play'] = model('app\admin\model\mox\play\Info')->where('id', 'in', $related_plays)->field('id, title,image,brief_introduction')->select();
                    });
            }
            // 返回JSON格式数据
            return json([
                'total' => $list->total(),
                'rows'  => $list->items()
            ]);
        }

        // 非AJAX请求返回视图
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['user_id'] = $this->auth->user_id;
                $params['create_time'] = time();
                $this->model->save($params);
                //关联剧目
                // if ($params['related_plays']) {
                //     //查询刚刚添加的人物id
                //     $character_id = $this->model->getLastInsID();
                //     $related_plays = explode(',', $params['related_plays']);
                //     $plays = model('app\admin\model\mox\play\Info')->where('id', 'in', $related_plays)->field('id, title,image,related_persons')->select();
                //     foreach ($plays as $k => $v) {
                //         $related_persons = explode(',', $v['related_persons']);
                //         //如果人物id不在剧目相关人物中，则添加
                //         if (!in_array($character_id, $related_persons)) {
                //             $related_persons[] = $character_id;
                //         }
                //         //去重
                //         $related_persons = array_unique($related_persons);
                //         $related_persons = implode(',', $related_persons);
                //         model('app\admin\model\mox\play\Info')->where('id', $v['id'])->update(['related_persons' => $related_persons]);
                //     }
                // }
                $this->success();
            } else {
                $this->error();
            }
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        //获取人物相关剧目
        $row_related_plays = explode(',', $row['related_plays']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['user_id'] = $this->auth->user_id;
                $params['update_time'] = time();
                $this->model->save($params, ['id' => $ids]);
                //关联剧目
                // if ($params['related_plays']) {
                //     $character_id = $ids;
                //     //获取$row_related_plays和$params['related_plays']的差集
                //     $diff = array_diff($row_related_plays, explode(',', $params['related_plays']));
                //     //如果差集不为空，则删除差集中的剧目相关人物
                //     if (!empty($diff)) {
                //         //查询差集中的剧目
                //         $plays = model('app\admin\model\mox\play\Info')->where('id', 'in', $diff)->field('id, title,image,related_persons')->select();
                //         foreach ($plays as $k => $diff_v) {

                //             $diff_related_persons = explode(',', $diff_v['related_persons']);
                //             //如果人物id在剧目相关人物中，则删除
                //             if (in_array($character_id, $diff_related_persons)) {
                //                 unset($related_persons[array_search($character_id, $diff_related_persons)]);
                //             }
                //             //去重
                //             $diff_related_persons = array_unique($diff_related_persons);
                //             $diff_related_persons = implode(',', $diff_related_persons);
                //             model('app\admin\model\mox\play\Info')->where('id', $diff_v['id'])->update(['related_persons' => $diff_related_persons]);
                //         }
                //     }

                //     //查询刚刚添加的人物id
                //     $related_plays = explode(',', $params['related_plays']);
                //     $plays = model('app\admin\model\mox\play\Info')->where('id', 'in', $related_plays)->field('id, title,image,related_persons')->select();
                //     foreach ($plays as $k => $v) {
                //         $related_persons = explode(',', $v['related_persons']);
                //         //如果人物id不在剧目相关人物中，则添加
                //         if (!in_array($character_id, $related_persons)) {
                //             $related_persons[] = $character_id;
                //         }
                //         //去重
                //         $related_persons = array_unique($related_persons);
                //         $related_persons = implode(',', $related_persons);
                //         model('app\admin\model\mox\play\Info')->where('id', $v['id'])->update(['related_persons' => $related_persons]);
                //     }
                // }
                $this->success();
            } else {
                $this->error();
            }
        }
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
}
